package com.alibaba.csp.sentinel.dashboard.rule.nacos.param;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component("paramRuleNacosPublisher")
public class ParamRuleNacosPublisher implements DynamicRulePublisher<List<ParamFlowRuleEntity>> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<List<ParamsFlowRuleEntity>, String> converter;

    @Override
    public void publish(String appNme, List<ParamFlowRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(appNme, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        //  转换
        List<ParamsFlowRuleEntity> list = rules.stream().map(rule -> {
            ParamsFlowRuleEntity entity = ParamsFlowRuleEntity.fromParamFlowRule(rule.getApp(), rule.getIp(), rule.getPort(), rule.getRule());
            entity.setId(rule.getId());
            entity.setApp(appNme);
            entity.setGmtCreate(rule.getGmtCreate());
            entity.setGmtModified(rule.getGmtModified());
            return entity;
        }).collect(Collectors.toList());
        String name = appNme + NacosConfigUtil.PARAM_FLOW_DATA_ID_POSTFIX;
        configService.publishConfig(name, NacosConfigUtil.GROUP_ID, converter.convert(list));
    }
}